import { defineStore } from 'pinia'
import { ref, watch, computed } from 'vue'

export type ThemeMode = 'light' | 'dark' | 'auto'

export const useThemeStore = defineStore('theme', () => {
  // 主题模式：light | dark | auto
  const themeMode = ref<ThemeMode>('light')
  
  // 实际应用的主题（auto模式下会根据系统偏好计算）
  const currentTheme = computed<'light' | 'dark'>(() => {
    if (themeMode.value === 'auto') {
      // 检测系统主题偏好
      if (typeof window !== 'undefined' && window.matchMedia) {
        return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'
      }
      return 'light'
    }
    return themeMode.value
  })

  // 系统主题变化监听器
  let systemThemeListener: ((e: MediaQueryListEvent) => void) | null = null

  // 初始化主题（从用户偏好或localStorage加载）
  const initTheme = async () => {
    // 优先从localStorage读取（可能已从用户偏好设置中同步）
    const savedTheme = localStorage.getItem('theme') as ThemeMode | null
    if (savedTheme && ['light', 'dark', 'auto'].includes(savedTheme)) {
      themeMode.value = savedTheme
    } else {
      // 默认使用light主题
      themeMode.value = 'light'
    }
    
    // 应用主题
    applyTheme()
    
    // 设置系统主题监听（仅在auto模式下）
    setupSystemThemeListener()
  }
  
  // 从用户偏好加载主题（在用户登录后调用）
  const loadThemeFromPreferences = (userTheme?: ThemeMode) => {
    if (userTheme && ['light', 'dark', 'auto'].includes(userTheme)) {
      themeMode.value = userTheme
      localStorage.setItem('theme', userTheme)
      applyTheme()
      setupSystemThemeListener()
    }
  }

  // 设置系统主题监听器
  const setupSystemThemeListener = () => {
    // 移除旧的监听器
    if (systemThemeListener && typeof window !== 'undefined' && window.matchMedia) {
      const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)')
      if (mediaQuery.removeEventListener) {
        mediaQuery.removeEventListener('change', systemThemeListener)
      } else if (mediaQuery.removeListener) {
        mediaQuery.removeListener(systemThemeListener)
      }
      systemThemeListener = null
    }

    // 仅在auto模式下监听系统主题变化
    if (themeMode.value === 'auto' && typeof window !== 'undefined' && window.matchMedia) {
      const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)')
      systemThemeListener = () => {
        applyTheme()
      }
      // 使用addEventListener（现代浏览器支持）
      if (mediaQuery.addEventListener) {
        mediaQuery.addEventListener('change', systemThemeListener)
      } else if (mediaQuery.addListener) {
        // 兼容旧浏览器
        mediaQuery.addListener(systemThemeListener)
      }
    }
  }

  // 应用主题到DOM
  const applyTheme = () => {
    if (typeof document === 'undefined') return
    
    const theme = currentTheme.value
    const html = document.documentElement
    const body = document.body
    
    // 移除旧的主题类
    html.classList.remove('theme-light', 'theme-dark')
    body.classList.remove('theme-light', 'theme-dark')
    
    // 添加新的主题类
    html.classList.add(`theme-${theme}`)
    body.classList.add(`theme-${theme}`)
    
    // 设置data-theme属性（用于CSS变量）
    html.setAttribute('data-theme', theme)
    body.setAttribute('data-theme', theme)
    
    // 确保背景色立即应用
    html.style.backgroundColor = ''
    body.style.backgroundColor = ''
    
    // 强制重新计算样式（确保CSS变量生效）
    void html.offsetHeight
  }

  // 设置主题
  const setTheme = (mode: ThemeMode) => {
    themeMode.value = mode
    localStorage.setItem('theme', mode)
    applyTheme()
    
    // 重新设置系统主题监听器
    setupSystemThemeListener()
  }

  // 切换主题（在light和dark之间切换，不包括auto）
  const toggleTheme = () => {
    const newTheme = currentTheme.value === 'light' ? 'dark' : 'light'
    setTheme(newTheme)
  }

  // 监听主题模式变化
  watch(themeMode, (newMode) => {
    applyTheme()
    setupSystemThemeListener()
  })

  return {
    themeMode,
    currentTheme,
    initTheme,
    setTheme,
    toggleTheme,
    loadThemeFromPreferences
  }
})

